<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error.sync="error"
    error-text="加载失败,请点击重试"
    :immediate-check="false"
    @load="onLoad"
  >
 <comment-item
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @reply-click="$emit('reply-click', $event)"
    />
  </van-list>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item'
export default {
  name: 'CommentList',
  components: { CommentItem },
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      // default，默认值，如果是数组或者对象，需要通过函数的形式返回
      default: () => []
    },
    type: {
      type: String,
      // 自定义 Prop 数据验证
      validator (value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    }
  },
  data () {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null,
      limit: 10,
      error: false
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loading = true
    this.onLoad()
  },
  mounted () {},
  methods: {

    async onLoad () {
      try {
        // 1 请求数据
        const { data } = await getComments({
          type: this.type, // a 是对文章的评论 c是对评论的回复
          source: this.source.toString(), // 源id  文章id 或 评论id
          offset: this.offset,
          limit: this.limit
        })

        // 2 把数据添加到列表中
        const { results } = data.data
        this.list.push(...results)
        // 把文章评论总量传到外部
        this.$emit('onload-success', data.data)
        // 3 将 loading 设置为 false
        this.loading = false
        // 4 判断是否有数据
        if (results.length) {
          // 有就更新获取下一页的数据页码
          this.offset = data.data.last_id
        } else {
          // 没有就将 finished 设置结束
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    }

  }
}
</script>

<style scoped lang="less">
</style>
